#!/bin/bash -e

function info() {
    echo Usage: `basename $0` '[-p] bam chr pos'
    echo
    echo -e "\t umi must be at read id's last field, seprated by ':'."
    exit 1
}

while getopts ":p:f:" opt; do
    case  $opt  in
        p) out_prefix=$OPTARG;;
        f) suffix=$OPTARG;;
        *) info;;
    esac
done
shift $(($OPTIND - 1))

if [ $# -lt 3 ]; then info; fi

export var=/mnt/ilustre/app/medical/tools/script/var
. $var
chr=$2
pos=$3
((pos0 = $pos -1))

echo -e "$chr\t$pos0\t$pos" > $out_prefix.${chr}_${pos}.bed
samtools view -b -L $out_prefix.${chr}_${pos}.bed $1> $out_prefix.${chr}_${pos}.bam

samtools view $out_prefix.${chr}_$pos.bam|cut -f1|awk 'BEGIN{FS=":"}{print $NF}'|sort|uniq -c|sed 's/^  *//g; s/ /\t/'|sort -k1rn > $out_prefix.${chr}_$pos.umi.freq.txt
